package cn.cmeizu.spring6.resource;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.UrlResource;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author cmeizu
 * @date 2023/2/19 13:49
 * 演示访问系统文件资源
 */
public class FileSystemResourceDemo {
  public static void main(String[] args) {
    //相关路径和绝对路径都可以
    String absPath = "/Users/apple/cmeizu/code/spring6/cmeizu.txt";
    String filePath = "test.txt";
    loadFileResource(absPath);

    loadFileResource(filePath);

  }

  /**
   * 访问前缀是http,file
   */
  public static void loadFileResource(String path) {
    //创建Resource实现类的对象 FileSystemResource
    FileSystemResource resource = new FileSystemResource(path);
    //获取资源信息
    System.out.println("url.getFilename() = " + resource.getFilename());
    System.out.println("url.getInputStream().read() = " + resource.getDescription());

    try {
      InputStream in = resource.getInputStream();
      byte[] b = new byte[1024];
      while (in.read(b) != -1) {
        System.out.println("new String(b) = " + new String(b).trim());
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
